<template>
  <div class="bind-email">
    <el-form
      :model="state.emailParam"
      :rules="state.rules"
      ref="ruleForm"
      class="demo-ruleForm"
    >
      <el-form-item prop="user_email" class="mb-20">
        <el-input
          v-model="state.emailParam.user_email"
          :placeholder="$t('formTip.emailTip')"
        ></el-input>
      </el-form-item>
      <el-form-item prop="verification_code" class="mb-20">
        <sendCode
          :fond="2"
          :param="state.emailParam"
          @getKey="getKey"
          @inputCode="inputCode"
        />
      </el-form-item>
      <div class="btn radius login-btn text-16 share-color" @click="submitForm">
        {{ $t("formTip.comfirm") }}
      </div>
    </el-form>
  </div>
</template>

<script>
import sendCode from "@/components/sendCode/SendCode.vue";
import { reactive, ref, nextTick } from "vue";
import { updateEmail } from "@/api/user";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";

export default {
  name: "bindEmail",
  components: { sendCode },
  props: {
    param: Object
  },
  emits: ["bindSuccess"],
  setup(props, { emit }) {
    const { t } = useI18n();
    const state = reactive({
      emailParam: { ...props.param, type: "bind" },
      rules: {
        user_email: [
          {
            required: true,
            message: "*" + t("formTip.emailTip"),
            trigger: "blur"
          }
        ],
        verification_code: [
          {
            required: true,
            message: "*" + t("formTip.codeTip"),
            trigger: "blur"
          }
        ]
      }
    });
    const ruleForm = ref();
    const inputCode = code => {
      state.emailParam.verification_code = code;
    };
    const getKey = key => {
      state.emailParam.key = key;
    };
    const submitForm = () => {
      console.log(state.emailParam);
      ruleForm.value.validate(valid => {
        if (valid) {
          updateEmail(state.emailParam)
            .then(res => {
              if (res.code === 200) {
                ElMessage({
                  type: "success",
                  message: res.message
                });
                nextTick(() => {
                  emit("bindSuccess", false);
                });
              }
            })
            .catch(err => {
              ElMessage.error(err.message);
            });
        } else {
          console.log("error submit!!", state.emailParam);
          return false;
        }
      });
    };
    return {
      state,
      submitForm,
      inputCode,
      ruleForm,
      getKey
    };
  }
};
</script>

<style scoped lang="less">
.bind-email {
  width: 100%;
}
.mb-20 {
  margin-bottom: 20px;
}
.mb-50 {
  margin-bottom: 50px;
}
.btn {
  height: 46px;
  line-height: 46px;
}
</style>
